const Cluster = require('../models/clusterModel')
// queueService.js
const Queue = require('better-queue')
const { get } = require('../utils/request')
// 初始化队列
const queue = new Queue(
  async (task, done) => {
    const { action, payload } = task

    switch (action) {
      case 'register':
        // 注册主机
        try {
          const newCluster = new Cluster({
            ...payload,
            lastHeartbeat: Date.now(),
            onlineTime: 0
          })
          const savedCluster = await newCluster.save()
          done(null, savedCluster)
        } catch (error) {
          done(error)
        }
        break

      case 'heartbeat':
        // 心跳检测，更新主机状态
        try {
          const cluster = await Cluster.findById(payload.id)
          // 当前一次心跳状态为true，则表示设备正常运行，此时累加时长
          let Time = cluster.onlineTime
          if (cluster.onlineStatus) {
            Time += Date.now() - cluster.lastHeartbeat
          }
          const updatedCluster = await Cluster.findByIdAndUpdate(
            { _id: payload.id }, // 使用 _id 来定位特定 Cluster
            {
              lastHeartbeat: Date.now(),
              onlineStatus: true,
              onlineTime: Time,
              performance: payload.performance // 更新性能指标
            },
            { new: true }
          )
          done(null, updatedCluster)
        } catch (error) {
          done(error)
        }
        break

      case 'offline':
        // 标记主机离线
        try {
          const cluster = await Cluster.find({ _id: { $in: payload.ids } })
          const requests = []
          for (let i = 0, len = cluster.length; i < len; i++) {
            const url = `${cluster[i].protocol}://${cluster[i].host}:${cluster[i].port}/cluster/offlineCluster`
            requests.push(get(url))
          }
          const res = await Promise.all(requests)
          console.log('向从机发送指令关闭心跳', res)
          const offlineCluster = await Cluster.updateMany(
            { _id: { $in: payload.ids } },
            { onlineStatus: false },
            { new: true }
          )
          done(null, offlineCluster)
        } catch (error) {
          done(error)
        }
        break
      case 'getData':
        try {
          const query = {}
          // 设置默认的分页参数
          let pageNo = parseInt(payload.pageNo) || 1
          let pageSize = parseInt(payload.pageSize) || 10
          const skip = (pageNo - 1) * pageSize
          if (payload.search) {
            query.host = new RegExp(payload.search, 'i') // 用于模糊搜索的正则表达式
          }
          // 计算总记录数
          const total = await Cluster.countDocuments(query)
          // 获得分页数据
          let records
          if (pageSize == -1) {
            records = await Cluster.find(query).sort({ createdAt: -1 }).exec()
          } else {
            records = await Cluster.find(query)
              .sort({ createdAt: -1 })
              .skip(skip)
              .limit(pageSize)
              .exec()
          }
          const resData = { records, total }
          done(null, resData)
        } catch (error) {
          done(error)
        }
        break
      case 'deleteCluster':
        try {
          const cluster = await Cluster.find({ _id: { $in: payload.ids } })
          const requests = []
          for (let i = 0, len = cluster.length; i < len; i++) {
            const url = `${cluster[i].protocol}://${cluster[i].host}:${cluster[i].port}/cluster/deleteCluster`
            requests.push(get(url))
          }
          const res = await Promise.all(requests)
          console.log('向从机发送指令删除从属机', res)
          // 删除数据库记录
          const resData = await Cluster.deleteMany({
            _id: { $in: payload.ids }
          })
          done(null, resData)
        } catch (error) {
          done(error)
        }
        break
      case 'startCluster':
        try {
          const cluster = await Cluster.find({ _id: { $in: payload.ids } })
          const requests = []
          for (let i = 0, len = cluster.length; i < len; i++) {
            const url = `${cluster[i].protocol}://${cluster[i].host}:${cluster[i].port}/cluster/startCluster`
            requests.push(get(url))
          }
          const res = await Promise.all(requests)
          console.log('向从机发送指令上线从属机', res)
          done(null, null)
        } catch (error) {
          done(error)
        }
        break
      case 'getprocessById':
        try {
          const cluster = await Cluster.findById(payload.clusterId)
          if (cluster) {
            const url = `${cluster.protocol}://${cluster.host}:${cluster.port}/cluster/getprocess`
            const res = await get(url)
            if (res.status) {
              done(null, res.data)
            }
          } else {
            done(null, null)
          }
        } catch (error) {
          done(error)
        }
        break
      case 'reloadProcess':
        try {
          const cluster = await Cluster.findById(payload.clusterId)
          if (cluster) {
            const url = `${cluster.protocol}://${cluster.host}:${cluster.port}/cluster/reloadProcess`
            const res = await get(url, {
              process: payload.processName
            })
            if (res && res.status) {
              done(null, res.data)
            } else {
              done(null, null)
            }
          } else {
            done(null, null)
          }
        } catch (error) {
          done(error)
        }
        break
      default:
        done(new Error('Unknown action type'))
    }
  },
  {
    // 任何队列的配置选项，根据需求来设置
  }
)

module.exports = queue
